package com.eeepay.eeepay_v2.api;

import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerchantSearchProto;
import cn.eeepay.api.grpc.nano.MerchantSearchServiceGrpc;
import io.grpc.ManagedChannel;

/**
 *
 * 描述：获取分润服务信息GRPC 获取
 * 作者：zhuangzeqin
 * 时间: 2017/6/1-10:53
 * 邮箱：zzq@eeepay.cn
 */
public class AgentServicesRequestAPI {
    private final int AGENTSERVICETASKID = 1001;//任务id
    private String[] bpId;//bpid 数组
    private String agentNo;//代理商编号

    private ResultCallBack resultCallBack;//设置监听接口

    /**
     * 构造函数；
     * @param bpId bpid 数组
     * @param agentNo 代理商编号
     */
    public AgentServicesRequestAPI(String[] bpId, String agentNo) {
        this.bpId = bpId;
        this.agentNo = agentNo;
    }

    /**
     * 设置监听接口
     *
     * @param resultCallBack
     */
    public void setResultCallBack(ResultCallBack resultCallBack) {
        this.resultCallBack = resultCallBack;
    }

    /**
     * 开始获取分润服务信息
     */
    public void getAdentServicesInfo() {
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, AGENTSERVICETASKID, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                MerchantSearchServiceGrpc.MerchantSearchServiceBlockingStub stub = MerchantSearchServiceGrpc
                        .newBlockingStub(channel).withDeadlineAfter(30, TimeUnit.SECONDS);
                MerchantSearchProto.AgentServicesRequest request = new MerchantSearchProto.AgentServicesRequest();
                //参数设置
                request.bpId = bpId;
                request.agentNo = agentNo;
                return stub.getAgentServices(request);
            }

            @Override
            public void updateUI(Object result, int taskId) {
                if (result == null)
                    return;
                MerchantSearchProto.AgentServicesResponse response = (MerchantSearchProto.AgentServicesResponse) result;
                if (!response.success) {//失败返回
                    if (resultCallBack != null)
                        resultCallBack.onFail(response.msg);
                    return;
                }
                //数组转换为集合list
                List<MerchantSearchProto.AgentServicesInfo> infoList = Arrays.asList(response.agentServices);
                if (resultCallBack != null)
                    resultCallBack.onSucess(infoList);

            }
        });
    }

    /**
     * 提供外围接口；通过接口回传
     */
    public interface ResultCallBack {
        void onFail(String msg);//失败返回；提示语

        void onSucess(List<MerchantSearchProto.AgentServicesInfo> infoList);//成功返回数据列表
    }
}
